<template>
    <div class="dict">
        <div class="dict-list">
            <div class="move-box">
                <RiskLeftModule
                    v-model="userName"
                    @on-handleNode="clickNode"
                    :placeholders="ltitleName"
                    :treeData="datas"
                    :leftHeight="leftHgt"
                    :currentKey="currentKey"
                    :key="currentKey"
                >
                    <template slot="ltitle">字典信息</template>
                </RiskLeftModule>

                <RiskRightModule v-model="rightInput" :rightPlace="rtitleName" :rightHeight="leftHgt" @on-keyup="selectDictData">
                    <p slot="rtitle">字典详情</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0232" @click="selectDictData">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0233" @click="dialogAddDic = true">新增字典</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0234" @click="addDictItem">新增字典项</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-dropdown @command="handleCommand">
                            <el-button type="primary" size="mini" v-authCode.show="B_0235"
                                >导出<i class="el-icon-arrow-down el-icon--right"></i
                            ></el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="Excel">导出 Excel</el-dropdown-item>
                                <el-dropdown-item command="Json">导出 Json</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0236" @click="putDictAlert = true">导入</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0237" @click="handleVisibleTemp('0')">启用</el-button>
                    </span>
                    <span slot="button">
                        <el-button type="danger" size="mini" v-authCode.show="B_0238" @click="handleVisibleTemp('1')">禁用</el-button>
                    </span>
                    <slot>
                        <el-table
                            :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0', 'text-align': 'center' }"
                            :cell-style="{ padding: '0' }"
                            :row-style="{ height: '35px' }"
                            :header-row-style="{ height: '35px', padding: '5px 0' }"
                            ref="multipleTable"
                            :data="tableData"
                            tooltip-effect="dark"
                            style="width: 100%"
                            border
                            @selection-change="handleSelectionChange"
                            size="mini"
                            height="68vh"
                            v-loading="loading"
                        >
                            <el-table-column type="selection" width="50" align="center"></el-table-column>
                            <el-table-column label="键" prop="dicKey"></el-table-column>
                            <el-table-column label="值" show-overflow-tooltip prop="dicValue"></el-table-column>
                            <el-table-column label="数据来源类型" :formatter="setStatus"></el-table-column>
                            <el-table-column label="状态">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.status == '0'">启用</span>
                                    <span v-else-if="scope.row.status == '1'">禁用</span>
                                    <span v-else>未知</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="160">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="primary"
                                        v-authCode="B_0239"
                                        icon="el-icon-edit"
                                        topTitle="编辑"
                                        size="mini"
                                        @on-click="editorInfo(scope.row)"
                                    ></RiskIconButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="dict" @page-change="currentChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
            </div>
            <!-- 新增数据字典 -->
            <yh-dialog drag title="新增数据字典" :visible.sync="dialogAddDic" width="500px" v-loading="loading">
                <el-form ref="form" label-width="120px" size="mini">
                    <el-form-item label="字典编码:">
                        <el-input class="dialog-form-width" maxlength="10" v-model="dictionary.dicCode" />
                    </el-form-item>
                    <el-form-item label="字典名称:">
                        <el-input class="dialog-form-width" v-model="dictionary.dicValue" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="dialogAddDic = false">
                        取 消
                    </el-button>
                    <el-button size="mini" type="primary" @click="addDicsData">确 定 </el-button>
                </div>
            </yh-dialog>

            <!-- 新增数据字典项 -->
            <yh-dialog drag title="新增数据字典项" :visible.sync="dialogAddDicitem" width="500px" v-loading="loading">
                <el-form ref="form" label-width="120px" size="mini">
                    <el-form-item label="字典编码:">
                        <el-input class="dialog-form-width" maxlength="10" v-model="dictionaryInfo.dicCode" />
                    </el-form-item>
                    <el-form-item label="键:">
                        <el-input class="dialog-form-width" v-model="dictionaryInfo.dicKey" />
                    </el-form-item>
                    <el-form-item label="值:">
                        <el-input class="dialog-form-width" v-model="dictionaryInfo.dicValue" />
                    </el-form-item>
                    <el-form-item label="数据来源:">
                        <el-select v-model="dictionaryInfo.sourceType" style="width:240px">
                            <el-option v-for="(value, key) in SourceTypes" :key="key" :label="value" :value="key"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态:">
                        <el-switch
                            v-model="dictionaryInfo.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-value="0"
                            inactive-value="1"
                        ></el-switch>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="dialogAddDicitem = false">
                        取 消
                    </el-button>
                    <el-button size="mini" type="primary" @click="addDictData">确 定 </el-button>
                </div>
            </yh-dialog>

            <!-- 编辑数据字典项 -->
            <yh-dialog drag title="编辑数据字典项" :visible.sync="dialogEditDicitem" width="500px" v-loading="loading">
                <el-form ref="form" label-width="120px" size="mini">
                    <el-form-item label="字典编码:">
                        <el-input class="dialog-form-width" v-model="editDictionaryInfo.dicCode" disabled />
                    </el-form-item>
                    <el-form-item label="键:">
                        <el-input class="dialog-form-width" v-model="editDictionaryInfo.dicKey" disabled />
                    </el-form-item>
                    <el-form-item label="值:">
                        <el-input class="dialog-form-width" v-model="editDictionaryInfo.dicValue" />
                    </el-form-item>
                    <el-form-item label="数据来源:">
                        <el-select v-model="editDictionaryInfo.sourceType" style="width:240px">
                            <el-option v-for="(value, key) in SourceTypes" :key="key" :label="value" :value="key"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态:">
                        <el-switch
                            v-model="editDictionaryInfo.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-value="0"
                            inactive-value="1"
                        ></el-switch>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="dialogEditDicitem = false">
                        取 消
                    </el-button>
                    <el-button size="mini" type="primary" @click="submitEditDict">确 定 </el-button>
                </div>
            </yh-dialog>

            <!-- 导入 -->
            <yh-dialog drag title="导入数据字典" :visible.sync="putDictAlert" width="650px" v-loading="loading">
                <div>
                    <el-button @click="putDictfile" type="primary">选择文件</el-button><i> {{ fileNames }} </i>
                    <input type="file" ref="putInput" style="display:none" @change="putDictfiles" />
                    <el-table
                        :data="putTableData"
                        style="width: 100%"
                        border
                        size="mini"
                        height="300px"
                        :header-cell-style="{ 'text-align': 'center' }"
                    >
                        <el-table-column label="键" prop="dicKey"></el-table-column>
                        <el-table-column label="值" show-overflow-tooltip prop="dicValue"></el-table-column>
                        <el-table-column label="数据来源类型" :formatter="setStatus"></el-table-column>
                        <el-table-column label="状态">
                            <template slot-scope="scope">
                                <span v-if="scope.row.status == '0'">启用</span>
                                <span v-else-if="scope.row.status == '1'">禁用</span>
                                <span v-else>未知</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="putDictAlert = false">
                        取 消
                    </el-button>
                    <el-button size="mini" type="primary" @click="putDictDatas">确 定 </el-button>
                </div>
            </yh-dialog>

            <yh-dialog drag :visible.sync="visibleTemp" width="500px" :close-on-click-modal="false">
                <template slot="title">
                    <span style="color:#fff">{{ visibleName }}字典项</span>
                    <span style="color:#c80000">(备注：已自动过滤已{{ visibleName }}的字典项)</span>
                </template>
                <div>
                    <p>{{ pendinglist.join(' , ') }}</p>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="visibleTemp = false">取 消</el-button>
                    <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
                </div>
            </yh-dialog>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { getCurrentPageData } from '@/utils/tools';
import { downLoadFile } from '@/utils/request';
import DictionConstUtil from '@/utils/diction-const-util';
import RiskLeftModule from '@/common/components/risk-left-module.vue';
import RiskRightModule from '@/common/components/risk-right-module.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import { filter } from 'vue/types/umd';
import XEUtils from 'xe-utils';
import RiskPagination from '@/common/components/risk-pagination.vue';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'DictList',
    components: {
        RiskLeftModule,
        RiskRightModule,
        RiskIconButton,
        RiskPagination,
    },
})
export default class DictList extends Vue {
    public $refs!: {
        click;
    };
    private userName: string = '';
    private rightInput: string = '';
    private ltitleName: string = '编号/名称';
    private rtitleName: string = '字典键/值';
    private leftHgt: string = 'calc(100vh - 70px)';
    private tableData = [];
    private tableDatas: any;
    private loading: boolean = false;
    private dialogAddDic: boolean = false;
    private dialogAddDicitem: boolean = false;
    private dialogEditDicitem: boolean = false;
    private currentKey: string = '';
    private visibleTemp: boolean = false; // 禁用/启用显示

    private visibleName: string = ''; // 显示的'禁用'/'启用'

    private pendinglist: any[] = []; // 待启用/禁用数据
    private dict: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };
    private dictionary = {
        // 字典
        dicCode: '',
        dicKey: '!',
        dicValue: '',
        sourceType: '1',
        status: '0',
    };
    private dictionaryInfo = {
        // 字典项
        dicCode: '',
        dicKey: '',
        dicValue: '',
        sourceType: '1',
        status: '0',
    };
    private editDictionaryInfo = {
        // 编辑字典项
        dicCode: '',
        dicKey: '',
        dicValue: '',
        sourceType: '',
        status: '0',
    };
    private NodeCode: string = ''; // 节点code
    // private SourceType: any[] = [
    //     { key: '1', label: '风控' },
    //     { key: '2', label: '恒生-主动' },
    //     { key: '3', label: '财汇' },
    //     { key: '4', label: '估值' },
    // ];

    private SourceTypes: any = {
        '1': '风控',
        '2': '恒生-主动',
        '3': '财汇',
        '4': '估值',
    };
    private tableClickList: any[] = [];
    private tableClickListKey: any[] = [];
    private putDictAlert: boolean = false; // 上传div
    private datas: any = []; //  左边tree的数据
    private putTableData: any[] = []; // 上传的数据
    private fileNames: string = ''; // 上传文件名

    mounted() {
        this.getAllDictionary();
    }

    // 表格选中项
    private handleSelectionChange(val: any): void {
        this.tableClickList = val;
        this.tableClickListKey = [];
        for (var i in val) {
            this.tableClickListKey.push(val[i].dicKey);
        }
    }

    // 获取字典信息
    private getAllDictionary(): void {
        this.$axios.get('/dic/allDicInfo').then((res: any) => {
            let local = [];
            for (let itme of res) {
                let datas = itme.dicCode + '-' + itme.dicValue;
                local.push({ label: datas, id: itme.dicCode });
            }
            this.datas = local;
            if (this.datas.length > 0) {
                this.currentKey = this.datas[0].id;
                this.NodeCode = this.NodeCode ? this.NodeCode : this.datas[0].id;
                this.dictionaryInfo.dicCode = this.NodeCode;
                this.getDictionaryData(this.datas[0].id);
            }
        });
    }

    // 节点数据
    private clickNode(data: any): void {
        this.NodeCode = data.id;
        this.dictionaryInfo.dicCode = data.id;
        this.getDictionaryData(data.id);
    }

    // 获取对应的表数据
    private getDictionaryData(code: any): void {
        let paging = {
            currentPage: 1,
            totalPage: 0,
            pageSize: 50,
        };
        let riskDictionary = {
            dicCode: code,
        };
        this.$axios
            .post('/dic/dicData/list', {
                paging: paging,
                riskDictionary: riskDictionary,
            })
            .then(res => {
                this.tableDatas = res;
                this.tableDatas.forEach(element => {
                    element.key = element.dicKey;
                });
                this.dict.total = this.tableDatas.length;
                this.tableData = getCurrentPageData(this.tableDatas, this.dict.currentPage, this.dict.pageSize);
            })
            .catch(() => {});
    }

    // 查询
    private selectDictData(): void {
        let a = this.handleDicSearchDetailFilter(this.rightInput);
        this.dict.total = a.length;
        this.tableData = getCurrentPageData(a, this.dict.currentPage, this.dict.pageSize);
    }

    private addDictItem(): void {
        this.dialogAddDicitem = true;
        this.dictionaryInfo.dicKey = '';
        this.dictionaryInfo.dicValue = '';
        this.dictionaryInfo.sourceType = '1';
        this.dictionaryInfo.status = '0';
    }

    // 过滤
    private handleDicSearchDetailFilter(param: any) {
        return this.tableDatas.filter(
            item =>
                !param ||
                item.dicKey.toLocaleUpperCase().includes(param.toLocaleUpperCase()) ||
                item.dicValue.toLocaleUpperCase().includes(param.toLocaleUpperCase())
        );
    }

    // 翻页
    private currentChange(): void {
        let a = this.handleDicSearchDetailFilter(this.rightInput);
        this.dict.total = a.length;
        this.tableData = getCurrentPageData(a, this.dict.currentPage, this.dict.pageSize);
    }

    // 转换
    private setStatus(row: any): void {
        return this.SourceTypes[row.sourceType];
    }

    // 新增字典项
    private addDictData(): void {
        if (!this.dictionaryInfo.dicCode) {
            this.yh_message_error('字典编码不能为空!');
            return;
        }
        if (!this.dictionaryInfo.dicKey) {
            this.yh_message_error('字典键不能为空！');
            return;
        }
        if (!this.dictionaryInfo.dicValue) {
            this.yh_message_error('字典值不能为空!');
            return;
        }
        this.loading = true;
        let data = this.dictionaryInfo;
        this.$axios
            .put('/dic/add', data)
            .then(res => {
                this.loading = false;
                this.dialogAddDicitem = false;
                this.getDictionaryData(this.NodeCode);
                this.dictionaryInfo.dicKey = '';
                this.dictionaryInfo.dicValue = '';
                this.dictionaryInfo.sourceType = '';
                this.yh_message_success('操作成功！');
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 编辑字典项
    private editorInfo(row: any): void {
        this.editDictionaryInfo = JSON.parse(JSON.stringify(row));
        this.dialogEditDicitem = true;
    }
    // 编辑字典项
    private submitEditDict(): void {
        if (!this.editDictionaryInfo.dicValue) {
            this.yh_message_error('字典值不能为空!');
            return;
        }
        this.loading = true;
        this.$axios
            .post('/dic/update', this.editDictionaryInfo)
            .then(res => {
                this.loading = false;
                console.log(this.NodeCode, 'nodeCode');

                this.getDictionaryData(this.NodeCode);
                this.dialogEditDicitem = false;
                this.yh_message_success('操作成功！');
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 新增字典
    private addDicsData(): void {
        if (!this.dictionary.dicCode) {
            this.yh_message_error('字典编码不能为空!');
            return;
        }
        if (!this.dictionary.dicValue) {
            this.yh_message_error('字典名称不能为空!');
            return;
        }
        let data = this.dictionary;
        this.loading = true;
        this.$axios
            .put('/dic/add', data)
            .then((res: any) => {
                this.loading = false;
                this.dialogAddDic = false;
                this.getAllDictionary();
                this.dictionary.dicCode = '';
                this.dictionary.dicValue = '';
                this.yh_message_success('操作成功！');
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 启用/禁用按钮(0启用，1禁用)
    private handleVisibleTemp(value: string): void {
        this.visibleName = value == '0' ? '启用' : '禁用';
        if (this.tableClickList.length < 1) {
            this.yh_message_success('请选择要' + this.visibleName + '的字典');
            return;
        }

        let data = this.tableClickList.filter(item => item.status != value);

        if (data.length < 1) {
            this.yh_message_success('选择字典中没有需要' + this.visibleName + '的字典');
            return;
        }
        this.pendinglist = XEUtils.map(data, item => item.dicKey);
        this.visibleTemp = true;
    }

    private onSubmit(): void {
        this.loading = true;
        if (this.visibleName == '禁用') {
            this.$axios
                .post('/dic/forbid', {
                    dicCode: this.NodeCode,
                    selectKeys: this.tableClickListKey,
                })
                .then(res => {
                    this.loading = false;
                    this.getDictionaryData(this.NodeCode);
                    this.visibleTemp = false;
                    this.yh_message_success('操作成功！');
                })
                .catch(() => {
                    this.visibleTemp = false;
                    this.loading = false;
                });
        } else {
            this.$axios
                .post('/dic/enable', {
                    dicCode: this.NodeCode,
                    selectKeys: this.tableClickListKey,
                })
                .then(res => {
                    this.loading = false;
                    this.getDictionaryData(this.NodeCode);
                    this.yh_message_success('操作成功！');
                    this.visibleTemp = false;
                })
                .catch(() => {
                    this.loading = false;
                    this.visibleTemp = false;
                });
        }
    }
    // 导出excl and json
    private handleCommand(val: string): void {
        if (val === 'Excel') {
            downLoadFile({
                url: '/dic/export/excel',
                method: 'post',
                data: {
                    dicCode: this.NodeCode,
                },
            });
        } else {
            downLoadFile({
                url: '/dic/export/json',
                method: 'post',
                data: {
                    dicCode: this.NodeCode,
                },
            });
        }
    }

    // 上传
    private putDictfile() {
        // eslint-disable-next-line no-unused-expressions
        this.$refs['putInput'].click();
    }

    // 选取文件
    private putDictfiles(e) {
        let files = e.currentTarget.files;
        new Promise((resolve, reject) => {
            let reader = new FileReader();
            if (!files || files.length === 0) {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject();
            }
            reader.readAsText(files[0]);
            reader.onload = () => {
                resolve(reader.result);
            };
            reader.onerror = error => {
                reject(error);
            };
        }).then((res: any) => {
            try {
                let data = JSON.parse(res);
                if (!(data instanceof Array)) {
                    this.yh_message_error('只能通过json导入');
                    return;
                }
                this.putTableData = data;
                this.fileNames = files[0].name;
            } catch (e) {
                this.yh_message_error('只能通过json导入');
            }
        });
    }

    // 导入
    private putDictDatas(): void {
        if (this.putTableData.length < 1) {
            this.yh_message_error('请上传需要导入的文件');
            return;
        }
        this.loading = true;
        this.$axios
            .post('/dic/import/json', this.putTableData)
            .then(res => {
                this.yh_message_warn('导入成功！');
                this.putTableData = [];
                this.fileNames = '';
                this.loading = false;
                this.getDictionaryData(this.NodeCode);
                this.putDictAlert = false;
            })
            .catch(() => {
                this.yh_message_warn('导入失败！');
                this.loading = false;
            });
    }
}
</script>
<style lang="scss" scoped>
.dict {
    .dict-list {
        .dict-r-slot {
            margin-right: 10px;
        }
    }

    .dialog-form-width {
        width: 240px;
    }

    .test-but {
        & /deep/ .el-button--mini {
            padding: 2px 8px !important;
        }
    }
}
</style>
